package com.micro.ai.files.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.files.entity.FileUploadRecord;
import com.micro.ai.files.service.FileUploadRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 文件上传记录控制器
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/file-upload-records")
@Tag(name = "文件上传记录管理", description = "分片上传记录的管理功能")
public class FileUploadRecordController {

    @Autowired
    private FileUploadRecordService fileUploadRecordService;

    /**
     * 创建上传记录
     */
    @PostMapping
    @PreAuthorize("hasAuthority('upload_record:create')")
    @Operation(summary = "创建上传记录", description = "创建新的分片上传记录")
    public ApiResponse<FileUploadRecord> create(@Valid @RequestBody FileUploadRecord record) {
        log.info("创建上传记录请求: uploadId={}, filename={}, totalChunks={}", 
                record.getUploadId(), record.getFilename(), record.getTotalChunks());
        
        FileUploadRecord result = fileUploadRecordService.create(record);
        return ApiResponse.success("创建成功", result);
    }

    /**
     * 更新上传记录
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('upload_record:update')")
    @Operation(summary = "更新上传记录", description = "更新上传记录信息")
    public ApiResponse<FileUploadRecord> update(
            @Parameter(description = "记录ID", required = true) @PathVariable String id,
            @Valid @RequestBody FileUploadRecord record) {
        
        FileUploadRecord result = fileUploadRecordService.update(id, record);
        return ApiResponse.success("更新成功", result);
    }

    /**
     * 删除上传记录
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('upload_record:delete')")
    @Operation(summary = "删除上传记录", description = "删除上传记录")
    public ApiResponse<Void> delete(
            @Parameter(description = "记录ID", required = true) @PathVariable String id) {
        
        fileUploadRecordService.delete(id);
        return ApiResponse.successVoid("删除成功");
    }

    /**
     * 获取上传记录详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('upload_record:view')")
    @Operation(summary = "获取上传记录详情", description = "根据ID获取上传记录详细信息")
    public ApiResponse<FileUploadRecord> getById(
            @Parameter(description = "记录ID", required = true) @PathVariable String id) {
        
        FileUploadRecord record = fileUploadRecordService.getById(id);
        if (record == null) {
            return ApiResponse.error("F0002", "上传记录不存在");
        }
        return ApiResponse.success(record);
    }

    /**
     * 根据上传ID获取记录
     */
    @GetMapping("/by-upload-id/{uploadId}")
    @PreAuthorize("hasAuthority('upload_record:view')")
    @Operation(summary = "根据上传ID获取记录", description = "根据上传会话ID获取上传记录")
    public ApiResponse<FileUploadRecord> getByUploadId(
            @Parameter(description = "上传会话ID", required = true) @PathVariable String uploadId) {
        
        FileUploadRecord record = fileUploadRecordService.getByUploadId(uploadId);
        if (record == null) {
            return ApiResponse.error("F0002", "上传记录不存在");
        }
        return ApiResponse.success(record);
    }

    /**
     * 更新上传进度
     */
    @PutMapping("/progress/{uploadId}")
    @PreAuthorize("hasAuthority('upload_record:update')")
    @Operation(summary = "更新上传进度", description = "更新分片上传的进度")
    public ApiResponse<Void> updateProgress(
            @Parameter(description = "上传会话ID", required = true) @PathVariable String uploadId,
            @Parameter(description = "已上传分片数", required = true) @RequestParam("uploadedChunks") int uploadedChunks) {
        
        fileUploadRecordService.updateProgress(uploadId, uploadedChunks);
        return ApiResponse.successVoid("更新成功");
    }

    /**
     * 完成上传
     */
    @PutMapping("/complete/{uploadId}")
    @PreAuthorize("hasAuthority('upload_record:update')")
    @Operation(summary = "完成上传", description = "标记上传已完成")
    public ApiResponse<Void> completeUpload(
            @Parameter(description = "上传会话ID", required = true) @PathVariable String uploadId) {
        
        fileUploadRecordService.completeUpload(uploadId);
        return ApiResponse.successVoid("完成成功");
    }

    /**
     * 取消上传
     */
    @PutMapping("/cancel/{uploadId}")
    @PreAuthorize("hasAuthority('upload_record:cancel')")
    @Operation(summary = "取消上传", description = "取消正在进行的上传")
    public ApiResponse<Void> cancelUpload(
            @Parameter(description = "上传会话ID", required = true) @PathVariable String uploadId) {
        
        fileUploadRecordService.cancelUpload(uploadId);
        return ApiResponse.successVoid("取消成功");
    }

    /**
     * 分页查询上传记录
     */
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('upload_record:view')")
    @Operation(summary = "分页查询上传记录", description = "支持多条件查询上传记录列表")
    public ApiResponse<Page<FileUploadRecord>> pageQuery(
            @Parameter(description = "页码", example = "1") @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @Parameter(description = "每页数量", example = "20") @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @Parameter(description = "租户ID") @RequestParam(value = "tenantId", required = false) String tenantId,
            @Parameter(description = "关键词") @RequestParam(value = "keyword", required = false) String keyword,
            @Parameter(description = "状态") @RequestParam(value = "status", required = false) String status) {
        
        Page<FileUploadRecord> page = fileUploadRecordService.pageQuery(pageNum, pageSize, tenantId, keyword, status);
        return ApiResponse.success(page);
    }
}

